
package com.zx.map.controller;

import com.zx.map.service.AgentInfoService;
import com.zx.map.service.SettleCardInfoService;
import com.zx.map.service.domain.AgentInfoDomain;
import com.zx.map.service.domain.agent.TransAgentDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.AgentSettleCardInfoModel;
import com.zx.map.service.model.SettleCardInfoModel;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.MobileUtils;
import com.zx.map.utils.SUConstants;
import com.zx.platform.dao.model.Roles;
import com.zx.platform.service.OperatorInfoService;
import com.zx.platform.service.RolesService;
import com.zx.platform.utils.*;
import com.zx.scp.service.ImageCommonHelper;
import com.zx.scp.service.model.ImageSettleResponse;
import com.zx.utils.WebUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manage/agentInfo")
public class AgentInfoController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(AgentInfoController.class);


	@Autowired
	private AgentInfoService agentInfoService;
	@Autowired
	private OperatorInfoService operatorInfoService;
	@Autowired
	private SettleCardInfoService settleCardInfoService;

	@Autowired//角色
	private RolesService rolesService;


	/**
	 * 表单提交日期绑定
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}


	/**
	 * 总代进入查询代理商页面
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryAgentList")
	public String queryAgentList(AgentInfoDomain domain, Model model,
	                             HttpServletRequest request) {

		try {// 初始化信息
			Integer pageNum = domain.getPageNum();
			Integer pageSize = domain.getPageSize();

			// 查找当前操作员对应的代理商
			//如果当前操作人员没有关联的代理商则设置默认为上海宝数新增
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
			List<Roles> rolesList;
			if(curAgentInfoModel==null) {
				rolesList = rolesService.getDownAgentRolesWithWillAgent(curAgentInfoModel);
			} else {
				rolesList = rolesService.getDownAgentRoles(curAgentInfoModel);
			}

			if (null == pageNum) {
				pageNum = 1;
			}
			if (null == pageSize) {
				pageSize = SUConstants.PAGE_COUNT;
			}
			domain.setPageNum(pageNum);
			domain.setPageSize(pageSize);
			if(SUConstants.AGENT_LEVEL_WILL.equals(domain.getAgentLevel())){
				domain.setIsDirect(1);
			}
			//作为查询条件查询直属商户
			if(domain.getIsDirect()>0&&curAgentInfoModel!=null){
			   domain.setParentAgentId(curAgentInfoModel.getAgentId());
			}

			Map map = agentInfoService.getPageByDomain(curAgentInfoModel, domain);
			List<AgentInfoModel> list = (List<AgentInfoModel>) map.get("list");
			int recordCount = Integer.valueOf(map.get("count").toString());
			// 页面信息
			if (pageSize * pageNum > recordCount + pageSize - 1) {
				pageNum = 1;
			}

			model.addAttribute("agentInfoList", list);
			model.addAttribute("pageNum", pageNum);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageCount", PmpUtils.getPageCount(recordCount, pageSize));
			model.addAttribute("recordCount", recordCount);
			model.addAttribute("model", domain);
			model.addAttribute("roleList", rolesList);
			return "/jsp/map/agentInfo/agentInfoList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 查询意愿代理商页面
	 * @param domain
	 * @param model
	 * @param request
	 */
	@RequestMapping("/queryWillAgentList")
	public String queryWillAgentList(AgentInfoDomain domain, Model model,
	                             HttpServletRequest request) {

		try {// 初始化信息
			Integer pageNum = domain.getPageNum();
			Integer pageSize = domain.getPageSize();
			// 查找当前操作员对应的代理商
			//如果当前操作人员没有关联的代理商则设置默认为上海宝数新增
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
			if (null == pageNum) {
				pageNum = 1;
			}
			if (null == pageSize) {
				pageSize = SUConstants.PAGE_COUNT;
			}
			domain.setPageNum(pageNum);
			domain.setPageSize(pageSize);
			//如果是代理商则查询代理商的直属意愿代理，平台看所有
			if(curAgentInfoModel!=null){
				domain.setParentAgentId(curAgentInfoModel.getAgentId());
			}
			domain.setAgentLevel(SUConstants.AGENT_LEVEL_WILL);
			Map map = agentInfoService.getWillAgentByDomain(domain);
			List<AgentInfoModel> list = (List<AgentInfoModel>) map.get("list");
			int recordCount = Integer.valueOf(map.get("count").toString());
			// 页面信息
			if (pageSize * pageNum > recordCount + pageSize - 1) {
				pageNum = 1;
			}
			model.addAttribute("agentInfoList", list);
			model.addAttribute("pageNum", pageNum);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageCount", PmpUtils.getPageCount(recordCount, pageSize));
			model.addAttribute("recordCount", recordCount);
			model.addAttribute("model", domain);
			return "/jsp/map/agentInfo/willAgentInfoList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 关闭三级代理权限
	 * @param agentInfoModel
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/closeAgent")
	@ResponseBody
	public Map<String,Object> closeAgent(AgentInfoModel agentInfoModel,Model model,
	                                     HttpServletRequest request){
		try {
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
			agentInfoModel.setAgentLevel(SUConstants.AGENT_LEVEL_WILL);
			return agentInfoService.closeAgent(agentInfoModel,curAgentInfoModel);
		}catch (Exception e){
			return CommonResponseUtils.failureResponse(SUConstants.SERVER_ERROR);
		}

	}


	/**
	 * 转让代理
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/transAgentPage")
	public String transAgentPage(Model model, HttpServletRequest request){
		return "/jsp/map/agentInfo/transAgentInfo";
	}

	@RequestMapping("/transAgent")
	@ResponseBody
	public Map<String,Object> transAgent(TransAgentDomain transAgentDomain, Model model,
	                                     HttpServletRequest request){
		try {
			String fromAccount=transAgentDomain.getFromAccount();
			if(MobileUtils.isNotPhone(fromAccount)){
				return CommonResponseUtils.failureResponse("待转让代理账户不合法");
			}

			String toAccount=transAgentDomain.getToAccount();
			if(MobileUtils.isNotPhone(toAccount)){
				return CommonResponseUtils.failureResponse("接收代理账户不合法");
			}

			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);

			return agentInfoService.transAgent(curAgentInfoModel,transAgentDomain);
		}catch (Exception e){
			return CommonResponseUtils.failureResponse(SUConstants.SERVER_ERROR);
		}

	}

	/**
	 * 弹出的新增修改页面
	 *
	 * @param agentInfoModel
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(AgentInfoModel agentInfoModel, Model model,
	                   HttpServletRequest request) {
		try {

			String agentId = agentInfoModel.getAgentId();
			if (agentId != "add" && StrUtils.isNotEmpty(agentId)) {
				agentInfoModel = agentInfoService.getModelByKey(agentId);
			}
			model.addAttribute("model", agentInfoModel);
			return "/jsp/map/agentInfo/agentInfoEdit";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 根据代理商id等  查询对应信息
	 *
	 * @param agentInfoModel
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryAgentInfoPage")
	public String queryAgentInfoPage(AgentInfoModel agentInfoModel, Model model,
	                                 HttpServletRequest request) {
		try {
			String agentId = agentInfoModel.getAgentId();
			//Map<String, Object> resultMap = new HashedMap();
			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);  // 查找当前操作员对应的代理商
			List<Roles> rolesList = rolesService.getDownAgentRoles(curAgentInfoModel);
			//resultMap.put("roleList", rolesList);

			if (StrUtils.isBlank(agentId)) {// 新增

			} else {
				agentInfoModel = agentInfoService.getModelByKey(agentId);
				//resultMap.put("agentInfoModel", agentInfoModel);
				model.addAttribute("agentInfoModel", agentInfoModel);
			}
			model.addAttribute("roleList", rolesList);

			return "/jsp/map/agentInfo/editAgentInfoPage";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}



	/**
	 * 编辑操作
	 *
	 * @return
	 */
	@RequestMapping("/saveOrUpdateAgentInfo")
	public String saveOrUpdateAgentInfo( @RequestParam("file") MultipartFile files[], AgentInfoModel agentInfoModel, Model model,
	                                                 HttpServletRequest request) {
		try {
			int i = 0;
			for (MultipartFile f : files) {
				i++;
				String fileName = f.getOriginalFilename();
				if (fileName == null || fileName.length() == 0) {
					continue;
				}
				// 对字节数组Base64编码
				BASE64Encoder encoder = new BASE64Encoder();
				ImageSettleResponse holdCard = ImageCommonHelper.getImageResponse(encoder
						.encode(f.getBytes()), agentInfoModel.getSysAccount());// 转换为base64编码

				if ("0000".equals(holdCard.getReturnCode())) {
					if (i == 1) {
						agentInfoModel.setLegalIndentityImg(holdCard
								.getImageKey());
					} else if (i == 2) {
						agentInfoModel.setBussinessImg(holdCard
								.getImageKey());
					} else {
						agentInfoModel.setSettleCardImg(holdCard
								.getImageKey());
					}
				} else {
					throw new RuntimeException("图片处理异常");
				}
			}

			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
			Map<String,Object> resultMap=agentInfoService.saveOrUpdateAgentInfo(agentInfoModel, curAgentInfoModel);
			return "redirect:/manage/agentInfo/queryAgentInfoPage?agentId="+agentInfoModel.getAgentId()+"&msg="+resultMap.get(SUConstants.CODE_KEY);

	} catch (Exception e) {
		log.error("内部异常", e);
		model.addAttribute("errorMsg", "出错了");
		return "/jsp/platform/error";
	}
	}


	/**
	 * 编辑操作
	 *
	 * @return
	 */
	@RequestMapping("/editAgentInfo")
	public String editAgentInfo(AgentSettleCardInfoModel agentModel,
	                            Model model, HttpServletRequest request) {
		try {
			AgentInfoModel currentAgentInfo = WebUtils.queryCurrentLoginAgentInfo(request);
			agentInfoService.editAgentInfo(agentModel, currentAgentInfo);
			return "redirect:/manage/agentInfo/list";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}


	/**
	 * 重置密码
	 *
	 * @return
	 */
	@RequestMapping("/resetPwd")
	@ResponseBody
	public Map<String, Object> resetPwd(AgentInfoModel model) {
		try {
			return operatorInfoService.resetPwdBySysAccount(model.getSysAccount());
		} catch (Exception e) {
			log.error("重置失败" + e.getMessage(), e);
			return CommonResponseUtils.successResponse("重置失败!");
		}
	}

	/**
	 * @return
	 */
	@RequestMapping("/existAgent")
	@ResponseBody
	public AgentInfoModel existAgent(AgentInfoModel model) {
		try {
			List<AgentInfoModel> agentInfoModel = agentInfoService.queryAgentInfoJustByModel(model);
			if (agentInfoModel != null) {
				model.setMsg("1");
			} else {
				model.setMsg("2");
			}
			model.setSuccess(true);
			log.debug("存在代理商");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("查询代理商失败");
			log.error("查询代理商失败" + e.getMessage(), e);
		}
		return model;
	}

	/**
	 * @return
	 */
	@RequestMapping("/existAgentAndSettleCard")
	@ResponseBody
	public AgentInfoModel existAgentAndSettleCard(AgentInfoModel model) {
		try {
			List list = agentInfoService.queryAgentInfoJustByModel(model);
			if (list != null && list.size() > 0) {
				model = (AgentInfoModel) list.get(0);
				String agentId = model.getAgentId();
				SettleCardInfoModel sModel = new SettleCardInfoModel();
				sModel.setSubjectType("2");
				sModel.setSubjectId(agentId);
				sModel = settleCardInfoService.getModelByInfo(sModel);
				if (sModel == null) {
					model.setMsg("3");
				} else {
					model.setMsg("1");
				}

			} else {
				model.setMsg("2");
			}
			model.setSuccess(true);
			log.debug("存在代理商");
		} catch (Exception e) {
			model.setSuccess(false);
			model.setMsg("查询代理商失败");
			log.error("查询代理商失败" + e.getMessage(), e);
		}
		return model;
	}

}
